import Vue from 'vue';
import utils from '@/common/utils/utils'
import aesTool from '@/common/aes/aes.js'
import config from '@/common/config/config.js'
let request = {};

var timeoutValue = 15000;
var debug = false;
var version = "1.0.0";


request.post = function({
	url,
	data,
	header = {},
	content_type,
	dataType="json",
	success,
	fail,
	customUrl,
	needEncryption = false,
	needCache,
	cacheParams,
	reload
}) {
	var cipher = data;
	var headerParams = {
		...header,
		"Content-type": "application/json",
		"token": uni.getStorageSync("token"),
		"version": version,
		"wx_app_id":config.wx_app_id
	}
	//是否是自定义url
	if (customUrl) {
		url = customUrl;
		if(dataType == 'application/x-www-form-urlencoded'){
			headerParams = {
				"Content-type": "application/x-www-form-urlencoded"
			}
		}
	} else {
		url = config.request_host + url;
		//是否需要缓存
		if (needCache) {
			//根据哪些参数缓存
			if (cacheParams) {
				var key = aesTool.encryption(cacheParams);
				var cache = uni.getStorageSync(key);
				if (cache) {
					success(cache);
					return;
				}
			}
		}
		
		if (debug) {
			console.log("params-------->" + JSON.stringify(data));
			console.log("headerParams-------->" + JSON.stringify(headerParams));
			console.log("url-------->" + url);
			console.log("needEncryption-------->" + needEncryption);
		}
		
		//是否需要加密
		if (needEncryption) {
			if (data) {
				cipher = {
					"cipher": aesTool.encryption(JSON.stringify(data))
				};
				headerParams = {
					...header,
					"Content-type": "application/json",
					"token": uni.getStorageSync("token"),
					"HTTP_X_REQUESTED_WITH": "XMLHttpRequest",
					"version": version,
					"wx_app_id":config.wx_app_id
				}
			}
		}
	}

	return new Promise((resolve, reject) => {

		uni.request({
			url: url,
			method: "POST",
			data: cipher,
			header: headerParams,
			timeout: timeoutValue,
			dataType: dataType,
			fail: (res) => {
				// console.log(res);
				let error = new Object();
				if (res.errMsg.indexOf("timeout") != -1) {
					error.code = -1001;
					error.message = "请求超时";
					uni.showToast({
						title: '请求超时',
						icon: 'none',
						duration: 2000
					})
				} else {
					error.code = -1;
					error.message = "网络异常";
				}
				fail(error);
			},
			success: (res) => {

				if (res.statusCode == 200) {
					//业务层的错误
					if (res.data.code === "401") {
						if (reload != 'reload') {
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}
						let error = new Object();
						error.message = res.data.message;
						error.code = res.data.code;
						uni.setStorageSync('token', null);
						fail(error);
					} else if (res.data.code === "200") {
						if (debug) console.log(res.data);
						let data = res.data.data;
						if (data && needEncryption) {
							data = JSON.parse(aesTool.deciphering(res.data.data));
						}
						if (needCache) {
							var key = aesTool.encryption(cacheParams);
							uni.setStorageSync(key, data);
						}
						success(data);
					} else {
						fail(res.data);
					}
				} else {
					//http层错误
					//request:fail timeout
					// console.log(res);
					fail(res);
				}
			}
		})
	});
};

request.get = function({
	url,
	data,
	header = {},
	success,
	fail,
	customUrl,
	needEncryption = false,
	needCache,
	cacheParams,
	reload
}) {

	if (debug) {
		console.log("params-------->" + JSON.stringify(data));
		console.log("url-------->" + url);
		console.log("customUrl-------->" + customUrl);
		console.log("needEncryption-------->" + needEncryption);
	}

	//是否是自定义url
	if (customUrl) {
		url = customUrl;
	} else {
		url = config.request_host + url;
	}

	return new Promise((resolve, reject) => {

		uni.request({
			url: url,
			method: "GET",
			// data: cipher,
			// header: headerParams,
			timeout: timeoutValue,
			dataType: 'json',
			fail: (res) => {
				// console.log(res);
				let error = new Object();
				if (res.errMsg.indexOf("timeout") != -1) {
					error.code = -1001;
					error.message = "请求超时";
					uni.showToast({
						title: '请求超时',
						icon: 'none',
						duration: 2000
					})
				} else {
					error.code = -1;
					error.message = "网络异常";
				}
				fail(error);
			},
			success: (res) => {

				if (res.statusCode == 200) {
					//业务层的错误
					if (res.data.code === "401") {
						if (reload != 'reload') {
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}
						let error = new Object();
						error.message = res.data.message;
						error.code = res.data.code;
						uni.setStorageSync('token', null);
						fail(error);
					} else if (res.data.code === "200") {
						if (debug) console.log(res.data);
						let data = res.data.data;
						if (data && needEncryption) {
							data = JSON.parse(aesTool.deciphering(res.data.data));
						}
						if (needCache) {
							var key = aesTool.encryption(cacheParams);
							uni.setStorageSync(key, data);
						}
						success(data);
					} else {
						// con
						
						fail(res.data);
					}
				} else {
					//http层错误
					//request:fail timeout
					// console.log(res);
					fail(res);
				}
			}
		})
	});
};

request.cache_image = function({
	image_url,
	call_back
}) {
	var image_name = aesTool.encryption(image_url);
	var local_url = uni.getStorageSync(image_name);
	if (local_url) return local_url;
	if (config.downMap.has(image_name)) return;
	config.downMap.set(image_name);

	uni.downloadFile({
		url: image_url,
		success: (res) => {

			if (res.statusCode === 200) {
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: function(res) {
						config.downMap.delete(image_name);
						console.log('下载完成：' + res.savedFilePath);
						var path = res.savedFilePath;
						uni.setStorageSync(image_name, path)
						call_back(path);
					},
					fail() {
						config.downMap.delete(image_name);
					}
				})
			} else {
				config.downMap.delete(image_name);
			}
		},
		fail(res){
			config.downMap.delete(image_name);
			console.log(res);
		}
	});
}

export default request;
